package ldh.im.dto.codec.binery;

import io.netty.buffer.ByteBuf;
import ldh.im.dto.base.Resp;
import ldh.im.dto.codec.BaseImCoder;
import ldh.im.util.LocalDateTimeUtil;

abstract class ResultCodec<T extends Resp> extends BaseImCoder<T> {

    @Override
    public void encode(T result, ByteBuf byteBuf) {
        checkEncode(result);
        if (result.getSuccessDataTime() == null) {
            byteBuf.writeLong(0L);
        } else {
            byteBuf.writeLong(LocalDateTimeUtil.getTime(result.getSuccessDataTime()));
        }
//        byteBuf.writeLong(result.getLocalSeq());
        writeString(byteBuf, result.getLocalSeq());
    }

    @Override
    public void decode(T result, ByteBuf byteBuf) {
        long time = byteBuf.readLong();
        if (time != 0L) {
            result.setSuccessDataTime(LocalDateTimeUtil.create(time));
        }
        result.setLocalSeq(readString(byteBuf));
    }

    protected void checkEncode(T result) {
        if (result.getLocalSeq() == null) {
            throw new RuntimeException("localSeq值不正确, localSeq=" + result.getLocalSeq());
        }
    }
}
